#include"seqlist.h"

void slinit(sl* ps)
{ 
	ps->arr = NULL; 
	ps->size = ps->capacity = 0;
}
void slcheckcapacity(sl* ps)
{
	if (ps->size == ps->capacity) 
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		sldatatype* tmp = (sldatatype*)realloc(ps->arr, newcapacity * sizeof(sldatatype)); 
		if (tmp == NULL) 
		{
			perror("realloc fail");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}
void slpushback(sl* ps, sldatatype x)
{
	assert(ps != NULL);
	if (ps->size == ps->capacity) 
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity; 
		sldatatype* tmp = (sldatatype*)realloc(ps->arr, newcapacity * sizeof(sldatatype));  
		if (tmp == NULL) 
		{
			perror("realloc fail");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
	ps->arr[ps->size] = x; 
	ps->size++; 
}
void slprint(sl* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++) 
	{
		printf("%d", ps->arr[i]);
	}
	printf("\n");
}
void slpushfront(sl* ps, sldatatype x)
{
	assert(ps);
	slcheckcapacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1]; 
	}
	ps->arr[0] = x;
	ps->size++;
}
 void slpopback(sl* ps)
{
	assert(ps);
	assert(ps->size);
	ps->size--;
}
void slpopfront(sl* ps)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0; i < ps->size - 1; i++) 
	{
		ps->arr[i] = ps->arr[i + 1]; 
	}
	ps->size--;
}
 void slinsert(sl* ps, int pos, sldatatype x) 
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	slcheckcapacity(ps);
	for (int i = ps->size; i >= pos; i++)
	{
		ps->arr[i] = ps->arr[i - 1]; 
	}
	ps->arr[pos] = x;
	ps->size++;
}
 void slerase(sl* ps, int pos)
{
	assert(ps);
 	assert(pos >= 0 && pos <= ps->size);
	for (int i = pos; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}
 /*void slfine(sl* ps, sldatatype x)
 {
	 assert(ps);
	 for (int i = 0; i < ps->size; i++)
	 {
		 if (ps->arr[i] == x)
		 {
			 return i;
		 }
	 }
	 return -1;
 }
*/
